<template>
  <view class="page">
    <view class="px-30rpx pt-30rpx">
      <view class="mb-30rpx">
        <u-search
          v-model="searchVal"
          placeholder="请输入名称搜索"
          :show-action="false"
          @search="handleSearch"
          @custom="handleSearch"
          @clear="handleSearch"
        />
      </view>
      <view class="current-select">
        <view class="font-bold general-text mr-30rpx">当前选中</view>
        <view
          class="general-text general-block"
          @tap="handleSelectTenant(currentSelect)"
        >
          {{ currentSelect.shortName || '请选择' }}
        </view>
      </view>
    </view>
    <view class="tenant-container">
      <view class="left-scroll-list">
        <scroll-view scroll-y class="h-full text-center">
          <u-collapse
            ref="collapse"
            accordion
            :value="openCollapse"
            :border="false"
            @change="handleChangeCollapse"
          >
            <template v-for="province in sourceData">
              <u-collapse-item
                :key="province.positionId"
                :title="province.position"
                :name="province.positionId"
              >
                <view class="flex flex-col">
                  <view
                    v-for="city in province.children"
                    :key="city.positionId"
                    class="city-name"
                    :class="{ active: city.positionId === activeCity }"
                    @tap="handleClickCity(city)"
                  >
                    {{ city.position }}
                  </view>
                </view>
              </u-collapse-item>
            </template>
          </u-collapse>
        </scroll-view>
      </view>

      <view class="right-scroll-list">
        <scroll-view scroll-y class="h-full">
          <view
            v-for="node in showRightPanel"
            :key="node.positionId"
            class="content-block"
          >
            <view v-if="!node.isLast" class="flex">
              <view class="county-name">{{ node.position }}</view>
              <view class="tenant-list">
                <view
                  v-for="tenant in node.children"
                  :key="tenant.tenantId"
                  class="general-text tenant-block"
                  :class="{
                    active: tenant.tenantId === currentSelect.tenantId
                  }"
                  @tap="handleSelectTenant(tenant)"
                >
                  {{ tenant.shortName }}
                </view>
              </view>
            </view>
            <view v-else class="flex flex-wrap">
              <view
                v-for="tenant in node.children"
                :key="tenant.tenantId"
                class="general-text tenant-block"
                :class="{ active: tenant.tenantId === currentSelect.tenantId }"
                @tap="handleSelectTenant(tenant)"
              >
                {{ tenant.shortName }}
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script lang="ts">
import { each, find } from 'lodash-es'
import { Component, Vue } from 'vue-property-decorator'

import { getTenantListApi } from '@/components/tenant-select/service'
import type { TenantAppType } from '@/components/tenant-select/TreeTyping'
import { TenantTreeNode } from '@/components/tenant-select/TreeTyping'
import { appStore } from '@/store/modules'

interface NodeType {
  positionId: string
  position: string
  isLast: boolean
  children: TenantAppType[]
}

@Component({ name: 'TenantSelect' })
export default class TenantSelect extends Vue {
  $refs!: {
    collapse: any
  }

  getOpenerEventChannel!: any

  public searchVal = ''

  public currentSelect: TenantAppType = {} as TenantAppType

  public sourceData: TenantTreeNode[] = []

  // 转换返回数据
  get showRightPanel() {
    const nodes: NodeType[] = []
    const lastNode: NodeType = {
      positionId: 'last',
      position: '经济技术开发区',
      isLast: true,
      children: []
    }

    each(this.rightPanel, (item) => {
      if ((item.tenantApps?.length ?? 0) > 1) {
        nodes.push({
          positionId: item.positionId,
          position: item.position,
          isLast: false,
          children: item.tenantApps ?? []
        })
      } else if (item.tenantApps?.length) {
        lastNode.children.push(item.tenantApps[0])
      }
    })
    nodes.push(lastNode)

    // const ll = clone(lastNode)
    // ll.isLast = false
    // nodes.unshift(ll)
    return nodes
  }

  public rightPanel: TenantTreeNode[] = []

  // 左侧折叠面板
  public openCollapse = ''
  // 左侧激活城市
  public activeCity = ''

  handleChangeCollapse([{ name }]: AnyObject[]) {
    this.openCollapse = name
  }

  handleClickCity(city: TenantTreeNode) {
    this.activeCity = city.positionId
    this.rightPanel = city.children ?? []
  }

  handleSelectTenant(tenant: TenantAppType) {
    this.currentSelect = tenant
    appStore.setSelectTenant(tenant.tenantId)
    this.handleNavigateBack()
  }

  async handleSearch(val: string) {
    try {
      await getTenantListApi(val).then((res) => {
        this.sourceData = res.children ?? []

        this.$nextTick(() => {
          this.$refs?.collapse?.init()
        })
      })
    } catch (e) {
      this.sourceData = [
        {
          position: '',
          positionId: '',
          positionType: 0,
          tenantApps: [],
          children: []
        }
      ]
    } finally {
      this.initSelect()
    }
  }

  async onLoad(query?: AnyObject) {
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on?.('selectTenant', (tenant: TenantAppType) => {
      this.currentSelect = tenant
    })

    getTenantListApi()
      .then((res) => {
        this.sourceData = res.children ?? []

        this.$nextTick(() => {
          this.$refs?.collapse?.init()
        })
      })
      .finally(this.initSelect)
  }

  initSelect() {
    // if (this.currentSelect.tenantId) {
    // } else {
    this.openCollapse = this.sourceData[0].positionId
    this.activeCity = this.sourceData[0].children?.[0].positionId || ''
    this.rightPanel = this.sourceData[0].children?.[0].children ?? []
    // }
  }

  findTreePath(tenantId: string) {
    const result: string[] = []
    const findPath = (tree: TenantTreeNode[]) => {
      try {
        each(tree, (item) => {
          if (
            item.tenantApps &&
            find(item.tenantApps, ['tenantId', tenantId])
          ) {
            result.push(item.positionId)
            throw Error('ok')
          } else if (item.children) {
            result.push(item.positionId)
            findPath(item.children)
          }
        })
      } catch (e) {
        console.log(e)
      }
    }
    findPath(this.sourceData)
    return result
  }

  handleNavigateBack() {
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit?.('selectTenant', this.currentSelect)
    uni.navigateBack({})
  }
}
</script>

<style lang="scss" scoped>
.page {
  height: 100vh;
  background-color: #ffffff;
  @apply flex flex-col;
}

.general-text {
  @apply text-26rpx text-[#333];
}

.tenant-block {
  @apply text-28rpx mr-40rpx mb-30rpx text-[#818181];

  &.active {
    @apply text-[#0052D9];
  }
}

.general-block {
  @apply py-15rpx px-20rpx bg-[#efefef];
}

.current-select {
  @apply pb-30rpx flex items-center;
}

.tenant-container {
  @apply flex-1 overflow-hidden flex;
}

.left-scroll-list {
  @apply h-full w-220rpx bg-secondary overflow-hidden;
  padding-top: $space-base;
  padding-bottom: calc(30rpx + $bs-height);
}

.right-scroll-list {
  @apply h-full flex-1 overflow-hidden px-20rpx;
  padding-top: $space-base;
  padding-bottom: calc(30rpx + $bs-height);
}

// fix collapse icon size
::v-deep .u-icon__icon {
  font-size: $font-size-2xs !important;
}

// fix collapse title
::v-deep .u-cell__title-text {
  font-size: $font-size-lg !important;
  color: $color-first-text !important;
}

// fix collapse item padding
::v-deep .u-collapse-item__content__text {
  padding: 0 !important;
}

// 城市名称
.city-name {
  @apply text-[#818181] text-26rpx py-30rpx transition-all duration-300;

  &.active {
    @apply text-[#0052D9] text-30rpx relative;

    &:after {
      content: '';
      position: absolute;
      left: calc(50% - 18rpx);
      bottom: 0;
      width: 30rpx;
      height: 6rpx;
      background-color: $color-primary;
    }
  }
}

// 大区块
.content-block {
  @apply p-20rpx;

  &:not(:last-child) {
    border-bottom: 2rpx solid rgba(0, 0, 0, 0.06);
  }
}

.county-name {
  @apply text-28rpx font-bold text-[#333333];
}

.tenant-list {
  @apply flex flex-col pl-30rpx;
}
</style>
